<?php

/**
 *   OPENSHOP 短信模块 之 控制器
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: sms.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      jiajun <jiajun@baison.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/cls_sms_baison.php');

//Modified by Jeff.jia on 20090423
//调整适合我们短信接口的实现
$action = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'display_help_info';

$flag = '';$alert = '';$account = '';$balance = '';$error_log = '';$endpoint = '';

/* 服务器是否支持WEBService调用,用来使用相应的短信服务功能 */
$loaded_exts = get_loaded_extensions();
$soap_enabled = in_array("soap", $loaded_exts)?TRUE:FALSE;    

if ($soap_enabled){
	$sms_baison = new sms_baison();
    $endpoint = $sms_baison->getSMSConfig();
    $account = $sms_baison->getSMSAccountConfig();  
    if ($action != 'edit_endpoint') {
        if ($action != 'add_endpoint') {
        // 短信服务终端 endpoint 初始化正常判断
        if ($endpoint != '' && eregi("\\.asmx$", $endpoint)) {
            $flag = 'normal';
            $alert = '您目前的短信服务终端配置正常';
            try{
                if(!$sms_baison->initWebService($endpoint)){
                    $error_log = 'error';
                    $flag = 'abnormal';
                    $action = 'default';    
                    $alert = '您没有正常配置短信服务终端,请确认后重新设置';
                }
            }catch(Exception $e){
                $error_log = 'error';
                $flag = 'abnormal';
                $action = 'default';    
                $alert = '您没有正常配置短信服务终端,请确认后重新设置'; 
            }
        }elseif( $endpoint != '' && !eregi("\\.asmx$", $endpoint)){
            $flag = 'abnormal';
            $action = 'default';
            $alert = '您没有正常配置短信服务终端,请确认后重新设置';
        }elseif ($endpoint == ''){
            $flag = 'abnormal';
            $action = 'default';
            $alert = '您目前还没有开通短信服务终端';
        }elseif ($action != 'set_account') {
            if ($account == '') {
                $action = 'default';
            }
        }
       }
    }

    if ($action == 'set_account' || $action == 'account_set' || ($action == 'edit_endpoint' && $account == '') || ($action == 'add_endpoint' && $account == '')) {
        $action = $action;
    }else{
        if ($account == '' || $error_log == 'error') {
            $action = 'default';
        }
    }
    $soap_flag = 'support';
}else{
	$action = 'default';
	$soap_flag = 'not_support';
}

switch ($action)
{
    /* 注册短信服务。*/
    case 'register' :
        $email      = isset($_POST['email'])    ? $_POST['email']       : '';
        $password   = isset($_POST['password']) ? $_POST['password']    : '';
        $domain     = isset($_POST['domain'])   ? $_POST['domain']      : '';
        $phone      = isset($_POST['phone'])    ? $_POST['phone']       : '';

        $result = $sms->register($email, $password, $domain, $phone);

        $link[] = array('text'  =>  '返回',
                        'href'  =>  'sms.php?act=display_my_info');

        if ($result === true)//注册成功
        {
            sys_msg('恭喜，您已成功注册短信服务！', 0, $link);
        }
        else
        {
            @$error_detail = $_LANG['server_errors'][$sms->errors['server_errors']['error_no']]
                          . $_LANG['api_errors']['register'][$sms->errors['api_errors']['error_no']];
            sys_msg('对不起，您注册短信服务失败。' . $error_detail, 1, $link);
        }

        break;

    /* 启用短信服务。 */
    case 'enable' :
        $username = isset($_POST['email'])      ? $_POST['email']       : '';
        //由于md5函数对空串也加密，所以要进行判空操作
        $password = isset($_POST['password']) && $_POST['password'] !== ''
                ? md5($_POST['password'])
                : '';

        $result = $sms->restore($username, $password);

        $link[] = array('text'  =>  '返回',
                        'href'  =>  'sms.php?act=display_my_info');

        if ($result === true)//启用成功
        {
            sys_msg('恭喜，您已成功启用短信服务！', 0, $link);
        }
        else
        {
            @$error_detail = $_LANG['server_errors'][$sms->errors['server_errors']['error_no']]
                          . $_LANG['api_errors']['auth'][$sms->errors['api_errors']['error_no']];
            sys_msg('对不起，您启用短信服务失败。' . $error_detail, 1, $link);
        }

        break;

    /* 注销短信特服信息 */
    case 'disable' :
        $result = $sms->clear_my_info();

        $link[] = array('text'  =>  '返回',
                        'href'  =>  'sms.php?act=display_my_info');

        if ($result === true)//注销成功
        {
            sys_msg('您已经成功注销短信服务。', 0, $link);
        }
        else
        {
            sys_msg('注销短信服务失败。', 1, $link);
        }

        break;

    /* 显示短信发送界面，如果尚未注册或启用短信服务则显示注册界面。 */
    case 'display_send_ui' :
        /* 检查权限 */
         admin_priv('sms_send');
         
         //$guide['level_one']=4;
         
        if ($sms->has_registered())
        {
            $smarty->assign('ur_here', '发送短信');
            assign_query_info();
            $guide['level_two']="sms_send_ui";
        }
        else
        {
            $smarty->assign('ur_here', '注册或启用短信账号');
            $smarty->assign('sms_site_info', $sms->get_site_info());
            
            assign_query_info();
        }
        $smarty->display("sms_register_ui.tpl");
        break;

    /* 发送短信 */
    case 'send_sms' :
        $phone     = isset($_POST['phone'])     ? $_POST['phone']       : '';
        $msg       = isset($_POST['msg'])       ? $_POST['msg']         : '';
        $send_date = isset($_POST['send_date']) ? $_POST['send_date']   : '';

        $result = $sms->send($phone, $msg, $send_date);

        $link[] = array('text'  =>  '返回' . '发送短信',
                        'href'  =>  'sms.php?act=display_send_ui');

        if ($result === true)//发送成功
        {
            sys_msg('恭喜，您的短信已经成功发送！', 0, $link);
        }
        else
        {
            @$error_detail = $_LANG['server_errors'][$sms->errors['server_errors']['error_no']]
                          . $_LANG['api_errors']['send'][$sms->errors['api_errors']['error_no']];
            sys_msg('对不起，在发送短信过程中发生错误。' . $error_detail, 1, $link);
        }

        break;

    /* 显示发送记录的查询界面，如果尚未注册或启用短信服务则显示注册界面。 */
    case 'display_send_history_ui' :
        /* 检查权限 */
         admin_priv('send_history');
        //$guide['level_one']=4;         
        if ($sms->has_registered())
        {
            $smarty->assign('ur_here', '发送记录');
            assign_query_info();
            $guide['level_two']="sms_send_history_query_ui";
        }
        else
        {
            $smarty->assign('ur_here', '注册或启用短信账号');
            $smarty->assign('sms_site_info', $sms->get_site_info());
            assign_query_info();
        }
        
        $smarty->display("sms_register_ui.tpl");
        break;

    /* 获得发送记录，如果客户端支持XSLT，则直接发送XML格式的文本到客户端；
       否则在服务器端把XML转换成XHTML后发送到客户端。
    */
    case 'get_send_history' :
        $start_date = isset($_POST['start_date'])   ? $_POST['start_date']  : '';
        $end_date   = isset($_POST['end_date'])     ? $_POST['end_date']    : '';
        $page_size  = isset($_POST['page_size'])    ? $_POST['page_size']   : 20;
        $page       = isset($_POST['page'])         ? $_POST['page']        : 1;

        $is_xslt_supported = isset($_POST['is_xslt_supported']) ? $_POST['is_xslt_supported'] : 'no';
        if ($is_xslt_supported === 'yes')
        {
            $xml = $sms->get_send_history_by_xml($start_date, $end_date, $page_size, $page);
            header('Content-Type: application/xml; charset=utf-8');
            //TODO:判断错误信息，链上XSLT
            echo $xml;
        }
        else
        {
            $result = $sms->get_send_history($start_date, $end_date, $page_size, $page);

            if ($result !== false)
            {
                $smarty->assign('sms_send_history', $result);
                $smarty->assign('ur_here', '发送记录');

                /* 分页信息 */
                $turn_page = array( 'total_records' => $result['count'],
                                    'total_pages'   => intval(ceil($result['count']/$page_size)),
                                    'page'          => $page,
                                    'page_size'     => $page_size);
                $smarty->assign('turn_page', $turn_page);
                $smarty->assign('start_date', $start_date);
                $smarty->assign('end_date', $end_date);

                assign_query_info();

                $smarty->display('sms_send_history.htm');
            }
            else
            {
                $link[] = array('text'  =>  '返回发送历史列表',
                                'href'  =>  'sms.php?act=display_send_history_ui');

                @$error_detail = $_LANG['server_errors'][$sms->errors['server_errors']['error_no']]
                              . $_LANG['api_errors']['get_history'][$sms->errors['api_errors']['error_no']];

                sys_msg('对不起，在查询过程中发生错误。' . $error_detail, 1, $link);
            }
        }

        break;

    /* 显示充值页面 */
    case 'display_charge_ui' :
        /* 检查权限 */
         admin_priv('sms_charge');
         //$guide['level_one']=4;
        if ($sms->has_registered())
        {
            $smarty->assign('ur_here', '账户充值');
            assign_query_info();
            $sms_charge = array();
            $sms_charge['charge_url'] = $sms->get_url('charge');
            $sms_charge['login_info'] = $sms->get_login_info();
            $smarty->assign('sms_charge', $sms_charge);
            $guide['level_two']="sms_send_ui";
        }
        else
        {
            $smarty->assign('ur_here', '注册或启用短信账号');
            $smarty->assign('sms_site_info', $sms->get_site_info());
            assign_query_info();
        }
        
        $smarty->display("sms_register_ui.tpl");
        break;
                  
    /* 显示充值记录的查询界面，如果尚未注册或启用短信服务则显示注册界面。 */
    case 'display_charge_history_ui' :
         /* 检查权限 */
         admin_priv('charge_history');
        // $guide['level_one']=4;
        if ($sms->has_registered())
        {
            $smarty->assign('ur_here', '充值记录');
            assign_query_info();
            $guide['level_two']="sms_charge_history_query_ui";
        }
        else
        {
            $smarty->assign('ur_here', '注册或启用短信账号');
            $smarty->assign('sms_site_info', $sms->get_site_info());
            assign_query_info();           
            $smarty->display("sms_register_ui.tpl");            
        }

        break;

    /* 获得充值记录，如果客户端支持XSLT，则直接发送XML格式的文本到客户端；
       否则在服务器端把XML转换成XHTML后发送到客户端。
    */
    case 'get_charge_history' :
        $start_date = isset($_POST['start_date'])   ? $_POST['start_date']  : '';
        $end_date   = isset($_POST['end_date'])     ? $_POST['end_date']    : '';
        $page_size  = isset($_POST['page_size'])    ? $_POST['page_size']   : 20;
        $page       = isset($_POST['page'])         ? $_POST['page']        : 1;

        $is_xslt_supported = isset($_POST['is_xslt_supported']) ? $_POST['is_xslt_supported'] : 'no';
        if ($is_xslt_supported === 'yes')
        {
            $xml = $sms->get_charge_history_by_xml($start_date, $end_date, $page_size, $page);
            header('Content-Type: application/xml; charset=utf-8');
            //TODO:判断错误信息，链上XSLT
            echo $xml;
        }
        else
        {
            $result = $sms->get_charge_history($start_date, $end_date, $page_size, $page);
            if ($result !== false)
            {
                $smarty->assign('sms_charge_history', $result);

                /* 分页信息 */
                $turn_page = array( 'total_records' => $result['count'],
                                    'total_pages'   => intval(ceil($result['count']/$page_size)),
                                    'page'          => $page,
                                    'page_size'     => $page_size);
                $smarty->assign('turn_page', $turn_page);
                $smarty->assign('start_date', $start_date);
                $smarty->assign('end_date', $end_date);

                assign_query_info();

                $smarty->display('sms_charge_history.htm');
            }
            else
            {
                $link[] = array('text'  =>  '返回充值历史列表',
                                'href'  =>  'sms.php?act=display_charge_history_ui');

                @$error_detail = $_LANG['server_errors'][$sms->errors['server_errors']['error_no']]
                              . $_LANG['api_errors']['get_history'][$sms->errors['api_errors']['error_no']];

                sys_msg('对不起，在查询过程中发生错误。' . $error_detail, 1, $link);
            }
        }

        break;

    /**
     *
     * 根据百胜软件公司提供的短信平台接口添加相应功能 
     * 
     */
        
    case 'edit_endpoint' :    
        /* 权限判断 */
        admin_priv('edit_endpoint');

        $smarty->assign('ur_here',     '设置短信服务终端');
    
        //$guide['level_one']=4;
        $smarty->assign('endpoint',$endpoint);

        assign_query_info();
        
        $smarty->display('sms_edit_endpoint.tpl');        
        break;

    case 'set_account' :    
        /* 权限判断 */
        admin_priv('set_account');

        $smarty->assign('ur_here',     '设置短信账户');
    
        //$guide['level_one']=4;
        $smarty->assign('guide',$guide);
        $smarty->assign('account',$account);
        
        assign_query_info();
        
        $smarty->display('sms_set_account.tpl');        
        break;        
        
        
    /* 显示短信发送页面 */
    case 'sms_send' :
         /* 检查权限 */
         admin_priv('charge_history');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '短信发送');
         
         assign_query_info();
         
         $smarty->display("sms_send.tpl");          
         break;
         
    case 'sendSMS' :
         /* 检查权限 */
         admin_priv('sendSMS');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '短信发送');
         $msg_content = trim($_POST['msg_content']);
         $sign_content  = trim($_POST['sign_content']);         
         $cell_number  = trim($_POST['cell_number']);
         $cell_array = explode(',', $cell_number);
         $result = array();
         foreach ($cell_array as $key => $cell){
            if ($cell != '') {
                $param = array(
                        'ProductId' => 'OpenShop',
                        'UserId' => $account,
                        'Password' => $sms_baison->getAccountPassword(),
                        'TargetNumber' => Encrypt_Phone(trim($cell)),
                        'MessageContent' => $msg_content,
                        'MessageSign' => $sign_content,
                        'PortNo' => '-1',
                        'InstructionId' => '-1',                                   
                        'StatusNotifyType' => '-1',
                        'StatusNotifyTarget' => ''  
                        );
                 $result[$cell] = $sms_baison->sendSMS($param);           
            }
         }
         assign_query_info();
         $smarty->assign('flag','displayResult');
         $smarty->assign('result',$result);
         $smarty->display("sms_send.tpl");           
         break;         

    /* 显示短信发送查询页面 */
    case 'sms_query' :
         /* 检查权限 */
         admin_priv('charge_history');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '发送查询');
         
         assign_query_info();
         
         $smarty->display("sms_query.tpl");          
         break;

    case 'sendQuery' :
         /* 检查权限 */
         admin_priv('sendQuery');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '发送查询');
         $msg_id  = trim($_POST['msg_id']);
         $msg_array = explode(',', $msg_id);
         $result = array();
         foreach ($msg_array as $key => $msg){
	        if ($msg != '') {
                $param = array(
                        'ProductId' => 'OpenShop',
                        'UserId' => $account,
                        'Password' => $sms_baison->getAccountPassword(),
                        'nMessageId' => trim($msg)      
                        );
                 $result[$msg] = $sms_baison->querySMSStatus($param);              
	        }
	     }       
	                 
         assign_query_info();
         $smarty->assign('flag','displayResult');
         $smarty->assign('result',$result);
         
         $smarty->display("sms_query.tpl");          
         break; 
                  
    /* 显示账户余额查询页面 */
    case 'sms_balance_query' :
         /* 检查权限 */
         admin_priv('charge_history');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '余额查询');
         
         assign_query_info();
         $smarty->assign('result',-1);
         
         $smarty->display("sms_balance_query.tpl");          
         break;         
         
    case 'balanceQuery' :
         /* 检查权限 */
         admin_priv('balanceQuery');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '余额查询');
         $param = array(
                        'ProductId' => 'OpenShop',
                        'UserId' => $account,
                        'Password' => $sms_baison->getAccountPassword(),     
                        );                     
         $result = $sms_baison->AccountBalanceQuery($param);    
                      
         assign_query_info();
         $smarty->assign('flag','displayResult');
         $smarty->assign('result',$result);
         
         $smarty->display("sms_balance_query.tpl");          
         break;  
                  
    /* 显示变更密码页面 */
    case 'sms_change_password' :
         /* 检查权限 */
         admin_priv('charge_history');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '密码修改');
         
         assign_query_info();
         $smarty->display("sms_change_password.tpl");            
         break;
         
    case 'changePassword' :
         /* 检查权限 */
         admin_priv('changePassword');
         //$guide['level_one']=4;
         $smarty->assign('ur_here', '密码修改');
         $new_password  = trim($_POST['new_password']);
         $param = array(
                        'ProductId' => 'OpenShop',
                        'UserId' => $account,
                        'Password' => $sms_baison->getAccountPassword(),
                        'NewPassword' => $new_password        
                        );                     
         $result = $sms_baison->accountChangePassword($param); 
         if ($result) {
         	$sms_baison->setAccountNewPassword($new_password);
         }
         
         assign_query_info();
         $smarty->assign('flag','displayResult');
         $smarty->assign('result',$result);         
         
         $smarty->display("sms_change_password.tpl");            
         break;         
         
    /* 显示内置短信列表页面 */
    case 'sms_bdin_list' :
         /* 检查权限 */
         admin_priv('sms_bdin_list');
         
         // 获得内置短信列表
         $list = $sms_baison->getBuildInfoList('0');
         
        // $guide['level_one']=4;
         $smarty->assign('full_page',    1);
         $smarty->assign('ur_here', '内置短信列表');
         $smarty->assign('action_link',  array('text' => '添加内置短信', 'href' => 'sms_buildin.php?act=add'));                  
         $sort_flag  = sort_flag($list['filter']);
         
         assign_query_info();
         $smarty->assign($sort_flag['tag'], $sort_flag['img']);
         $smarty->assign('buildinSMS',$list['item']);
         
         $smarty->assign('filter',       $list['filter']);
         $smarty->assign('record_count', $list['record_count']);
         $smarty->assign('page_count',   $list['page_count']);         
         
         $smarty->display("sms_bdin_list.tpl");            
         break;

    /* 显示内置签名列表页面 */
    case 'sms_bdin_sign_list' :
         /* 检查权限 */
         admin_priv('sms_bdin_list');
         // 获得内置签名列表
         $list = $sms_baison->getBuildInfoList('1');
         //$guide['level_one']=4;
         $smarty->assign('full_page',    1);

         $smarty->assign('ur_here', '内置签名列表');
         $smarty->assign('action_link',  array('text' => '添加内置签名', 'href' => 'sms_buildin_sign.php?act=add'));                  
         $sort_flag  = sort_flag($list['filter']);
         
         assign_query_info();
         $smarty->assign('buildinSign',$list['item']);
         $smarty->assign('filter',       $list['filter']);
         $smarty->assign('record_count', $list['record_count']);
         $smarty->assign('page_count',   $list['page_count']);  

         $smarty->display("sms_bdin_sign_list.tpl");            
         break;     

    case 'add_endpoint' :     

        /* 权限判断 */
        admin_priv('add_endpoint');

        $endpoint = trim($_POST['endpoint']);
         
        $sms_baison->setEndpoint($endpoint);
    
        /* 清除缓存 */
        clear_cache_files();

        $link[1]['text'] = '返回账户设置页面';
        $link[1]['href'] = 'sms.php?act=display_help_info';
    
        sys_msg('短信服务终端添加成功！', 0, $link);
        break;

     case 'account_set' : 
        /* 权限判断 */
        admin_priv('set_account');
    
        $user_name = trim($_POST['user_name']);
        $password  = trim($_POST['password']);
    
        $sms_baison->setAccount($user_name);
        $sms_baison->setAccountPassword($password);
        /* 清除缓存 */
        clear_cache_files();

        $link[1]['text'] = '返回账户设置页面';
        $link[1]['href'] = 'sms.php?act=display_help_info';

        sys_msg('短信账户设置成功！', 0, $link);
        break;  
                 
    /* 显示我的短信服务个人信息 */
    default :        
        $smarty->assign('ur_here', '账户信息');        
        //$guide['level_one']=4;          
        if ($soap_flag != 'not_support' && $endpoint != '' && $account != '' && $error_log != 'error' && $flag != 'abnormal') {
            $param = array(
                        'ProductId' => 'OpenShop',
                        'UserId' => $account,
                        'Password' => $sms_baison->getAccountPassword(),     
                        );                     
            $balance = $sms_baison->AccountBalanceQuery($param);         	
        }
        
        $smarty->assign('flag',$flag);
        $smarty->assign('soap_flag',$soap_flag);
        $smarty->assign('alert',$alert);  
        $smarty->assign('account',$account);
        $smarty->assign('balance',$balance);        
        $smarty->assign('endpoint',$endpoint);
        
        $smarty->display("display_help_info.tpl");
}

/**
 * 将输入的手机号码进行特定的加密处理
 *
 * @access  private
 * @param   string      $str     输入的手机号码
 *
 * @return  string      $s_encrypt  加密处理过后的字符串
 */
function Encrypt_Phone($s_phone){
    $CONST_1 = 3;
    $CONST_2 = 10;
    
    $key = rand(0,5000);
    $s_encrypt_header = substr('0000'.$key,strlen('0000'.$key)-4,4);
    
    $str_phone_array = str_split($s_phone);
    $temp_array = array();
    for($i = 0; $i < count($str_phone_array); $i++){
        $temp_array[$i] = chr(ord($str_phone_array[$i]) ^ ($key >> 8)) ;
        $key = (ord($temp_array[$i]) + $key) * $CONST_2 + $CONST_1;
        if ($temp_array[$i] == chr(0) ) {
            $temp_array[$i] = $str_phone_array[$i];
        }
    }
    
    $s_encrypt_body = implode($temp_array);
    $s_encrypt = $s_encrypt_header.StrToHex($s_encrypt_body);
    
    return $s_encrypt;
}

/**
 * 将输入的字符串按照16进制输出
 *
 * @access  private
 * @param   string      $str     输入的字符串
 *
 * @return  string      $result  按照16进制输出的字符串
 */
function StrToHex($str){
    $temp_str = '';
    
    $str_array = str_split($str);
    for($i = 0; $i < count($str_array); $i++){
        $temp_str .= sprintf('%2X', ord($str_array[$i]));
    }
    
    $temp_result = str_split($temp_str);
    for($i = 0; $i < count($temp_result); $i++){
        if ($temp_result[$i] == ' ') {
            $temp_result[$i] = '0';
        }
    }
    $result = implode($temp_result);
    return $result;
}    
?>